// 模拟菜品数据
let dishes = [];
let categories = [];

// DOM元素
const dishTable = document.getElementById('dishTable');
const dishModal = document.getElementById('dishModal');
const modalTitle = document.getElementById('modalTitle');
const dishForm = document.getElementById('dishForm');
const dishId = document.getElementById('dishId');
const nameInput = document.getElementById('name');
const priceInput = document.getElementById('price');
const categoryInput = document.getElementById('category');
const descriptionInput = document.getElementById('description');
const sortInput = document.getElementById('sort');
const imageUpload = document.getElementById('imageUpload');
const imageInput = document.getElementById('imageInput');
const imagePreview = document.getElementById('imagePreview');
const dishCount = document.getElementById('dishCount');
const searchInput = document.getElementById('searchName');
const noResults = document.getElementById('noResults');
const clearSearchBtn = document.getElementById('clearSearchBtn');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    // 新增API请求
    fetch('/menu/list')
        .then(response => response.json())
        .then(data => {
            dishes = data; // 更新菜单数据
            //categories = [...new Set(data.map(item => item.category))]; // 重新生成分类
            renderDishTable();
        })
        .catch(error => console.error('Error fetching menu:', error));

    // 事件监听
    document.getElementById('addDishBtn').addEventListener('click', openAddModal);
    document.getElementById('closeModal').addEventListener('click', closeModal);
    document.getElementById('cancelBtn').addEventListener('click', closeModal);
    document.getElementById('saveBtn').addEventListener('click', saveDish);

    // 实时搜索
    searchInput.addEventListener('input', function () {
        searchDishes();
        updateClearButton();
    });

    // 清空搜索框
    clearSearchBtn.addEventListener('click', function () {
        searchInput.value = '';
        searchDishes();
        updateClearButton();
    });

    // 图片上传
    imageUpload.addEventListener('click', () => imageInput.click());
    imageInput.addEventListener('change', handleImageUpload);

    // 初始更新清空按钮状态
    updateClearButton();
});

// 更新清空按钮显示状态
function updateClearButton() {
    if (searchInput.value.length > 0) {
        clearSearchBtn.classList.add('visible');
    } else {
        clearSearchBtn.classList.remove('visible');
    }
}

// 渲染菜品表格
function renderDishTable(dishesToRender = dishes) {
    dishTable.innerHTML = '';
    dishCount.textContent = dishesToRender.length;

    if (dishesToRender.length === 0) {
        noResults.style.display = 'block';
        return;
    }

    noResults.style.display = 'none';

    dishesToRender.forEach(dish => {
        const row = document.createElement('tr');

        // 根据分类获取样式
        let categoryClass = 'category-other';
        if (dish.category === '石锅菜') categoryClass = 'category-hot';
        else if (dish.category === '饮料') categoryClass = 'category-cold';
        else if (dish.category === '鱼粉') categoryClass = 'category-staple';
        else if (dish.category === '小吃') categoryClass = 'category-soup';

        row.innerHTML = `
                <td>${dish.id}</td>
                <td><img src="${dish.image || './img/logo.png'}" class="dish-image" alt="${dish.name}"></td>
                <td>${dish.name}</td>
                <td>${dish.description}</td>
                <td><span class="category-tag ${categoryClass}">${dish.category}</span></td>
                <td class="price">¥${dish.price.toFixed(2)}</td>
                <td>
                    <div class="actions">
                        <button class="action-btn edit-btn" data-id="${dish.id}">
                            <svg style="width: 18px;height: 18px;" t="1752028663626" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="11239" data-darkreader-inline-fill="" width="500" height="500"><path d="M824.883 440.883a48.333 48.333 0 0 1 96.717 0v290.15c0 120.781-101.427 241.767-220.262 241.767H271.462C150.016 972.8 51.2 881.971 51.2 765.03V317.082c0-117.607 99.584-214.682 220.262-214.682h311.655a48.333 48.333 0 1 1 0 96.717H271.462c-67.84 0-123.545 54.323-123.545 117.965v448c0 61.593 53.76 111.001 123.545 111.001h429.876c61.286 0 123.545-74.24 123.545-145.05V440.833zM775.22 240.998a51.2 51.2 0 0 1 0 72.397L452.608 636.11a51.2 51.2 0 0 1-72.448-72.397l322.765-322.714a51.2 51.2 0 0 1 72.397 0zM870.4 204.8a51.2 51.2 0 1 1 0-102.4 51.2 51.2 0 0 1 0 102.4z" p-id="11240" fill="#0ea5e9" data-darkreader-inline-fill="" style="--darkreader-inline-fill: var(--darkreader-background-0ea5e9, #0b85bc);"></path></svg>
                        </button>
                        <button class="action-btn delete-btn" data-id="${dish.id}">
                            <svg t="1752029200642" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="15365" data-darkreader-inline-fill="" width="500" height="500" style="width: 24px;height: 24px;"><path d="M757.397 323.67c17.602 0 31.354 15.122 29.782 32.585l-0.052 0.53-46.184 429.569C734.961 842 688.36 884.28 632.603 884.99l-1.693 0.009-290.07-0.69c-55.705-0.133-102.489-41.739-109.305-96.876l-0.194-1.675-46.493-428.948c-1.899-17.518 11.662-32.832 29.195-33.137l0.532-0.004h542.822zM402.692 452.969c-16.349 0-29.633 13.127-29.897 29.421l-0.004 0.495v204.81l0.008 0.706c0.375 16.196 13.615 29.21 29.893 29.21 16.349 0 29.633-13.127 29.897-29.421l0.004-0.495v-204.81l-0.008-0.706c-0.375-16.196-13.615-29.21-29.893-29.21z m156.004 0c-16.349 0-29.633 13.127-29.897 29.421l-0.004 0.495v204.81l0.008 0.706c0.375 16.196 13.615 29.21 29.893 29.21 16.349 0 29.633-13.127 29.897-29.421l0.004-0.495v-204.81l-0.008-0.706c-0.375-16.196-13.615-29.21-29.893-29.21z m268.403-210.153c16.514 0 29.901 13.394 29.901 29.916 0 16.286-13.007 29.533-29.195 29.908l-0.706 0.008H133.9c-16.514 0-29.901-13.394-29.901-29.916 0-16.286 13.007-29.533 29.195-29.908l0.706-0.008H827.1zM598.003 140c16.514 0 29.902 13.394 29.902 29.916 0 16.286-13.008 29.533-29.196 29.908l-0.706 0.008H362.758c-16.514 0-29.901-13.394-29.901-29.916 0-16.286 13.007-29.533 29.195-29.908l0.706-0.008h235.245z" fill="#ef4444" p-id="15366" data-darkreader-inline-fill="" style="--darkreader-inline-fill: var(--darkreader-background-ef4444, #9e0e0e);"></path></svg>
                        </button>
                    </div>
                </td>
            `;

        dishTable.appendChild(row);
    });

    // 添加编辑和删除事件
    document.querySelectorAll('.edit-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const id = parseInt(btn.getAttribute('data-id'));
            openEditModal(id);
        });
    });

    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const id = parseInt(btn.getAttribute('data-id'));
            deleteDish(id);
        });
    });
}

// 打开添加模态框
function openAddModal() {
    loadCategories();
    modalTitle.textContent = '添加菜品';
    dishForm.reset();
    dishId.value = '';
    imagePreview.style.display = 'none';
    imagePreview.src = null;
    dishModal.style.display = 'flex';
}

// 打开编辑模态框
function openEditModal(id) {
    loadCategories();
    const dish = dishes.find(d => d.id === id);
    if (dish) {
        modalTitle.textContent = '编辑菜品';
        dishId.value = dish.id;
        nameInput.value = dish.name;
        priceInput.value = dish.price;
        categoryInput.value = dish.category;
        descriptionInput.value = dish.description;
        sortInput.value = dish.sort || 0; // 设置排序值

        // 设置图片预览
        if (dish.image) {
            imagePreview.src = dish.image;
            imagePreview.style.display = 'block';
        } else {
            imagePreview.style.display = 'none';
        }

        dishModal.style.display = 'flex';
    }
}

// 新增分类加载函数
function loadCategories() {
        fetch('/menu/categories')
            .then(response => response.json())
            .then(data => {
                categories = data;
                setupCategoryInput();
                //showCategoryList();
            })
            .catch(error => console.error('加载分类失败:', error));
}

// 初始化分类输入框事件
function setupCategoryInput() {
    categoryInput.addEventListener('click', () => showCategoryList());
    categoryInput.addEventListener('input', (e) => showCategoryList(e.target.value));

    // 点击外部关闭列表
    document.addEventListener('click', (e) => {
        if (!e.target.closest('#category, #categoryList')) {
            document.getElementById('categoryList').style.display = 'none';
        }
    });
}

// 分类列表显示函数
function showCategoryList(filter = '') {
    const list = document.getElementById('categoryList');
    list.innerHTML = '';
    const filtered = categories.filter(c => c.toLowerCase().includes(filter.toLowerCase()));

    filtered.forEach(category => {
        const item = document.createElement('div');
        item.className = 'category-item';
        item.textContent = category;
        item.onclick = () => {
            categoryInput.value = category;
            list.style.display = 'none';
        };
        list.appendChild(item);
    });

    list.style.display = filtered.length ? 'block' : 'none';
}

// 关闭模态框
function closeModal() {
    dishModal.style.display = 'none';
}

// 保存菜品
async function saveDish() {
    const id = dishId.value;
    const formData = {
        id: id || null,
        name: nameInput.value.trim(),
        price: parseFloat(priceInput.value),
        category: categoryInput.value,
        sort: parseInt(sortInput.value) || 0, // 新增排序字段
        description: descriptionInput.value.trim(),
        image: imagePreview.src && !imagePreview.src.includes('null') ? imagePreview.src : null
    };

    if (!formData.name || !formData.price || !formData.category) {
        alert('请填写必填字段（名称、价格、分类）');
        return;
    }

    try {
        const response = await fetch('/menu/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });

        if (!response.ok) throw new Error('保存失败');

        // 保存成功后重新加载数据
        const newData = await fetch('/menu/list').then(r => r.json());
        dishes = newData;
        renderDishTable();
        closeModal();
    } catch (error) {
        console.error('保存错误:', error);
        alert('保存失败，请检查网络连接');
    }
}

// 删除菜品（需要同步修改）
async function deleteDish(id) {
    if (confirm('确定要删除这个菜品吗？')) {
        try {
            const response = await fetch(`/menu/delete/${id}`, {
                method: 'DELETE'
            });

            if (!response.ok) throw new Error('删除失败');

            // 删除成功后重新加载数据
            const newData = await fetch('/menu/list').then(r => r.json());
            dishes = newData;
            renderDishTable();
            searchDishes();
        } catch (error) {
            console.error('删除错误:', error);
            alert('删除失败，请检查网络连接');
        }
    }
}

// 实时搜索菜品
function searchDishes() {
    const searchTerm = searchInput.value.toLowerCase();

    if (!searchTerm) {
        renderDishTable();
        return;
    }

    const filtered = dishes.filter(dish => {
        return dish.name.toLowerCase().includes(searchTerm);
    });

    renderDishTable(filtered);
}

// 处理图片上传
async function handleImageUpload(e) {
    const file = e.target.files[0];
    if (file) {
        try {
            const formData = new FormData();
            formData.append('file', file);

            const response = await fetch('/menu/upload', {
                method: 'POST',
                body: formData
            });

            const data = await response.json();
            imagePreview.src = data.path; // 直接使用返回的路径
            imagePreview.style.display = 'block';
        } catch (error) {
            console.error('上传失败:', error);
            alert('图片上传失败');
        }
    }
}